import Event from "sap/ui/base/Event";
import { BaseController } from "sap/ui/demo/nav/controller/BaseController";
import JSONModel from "sap/ui/model/json/JSONModel";
import { EmployeeResumeRouteArgs } from "sap/ui/demo/nav/interfaces/IEmployee.controller";



const _aValidTabKeys = ["Info", "Projects", "Hobbies", "Notes"];

/**
 * @namespace sap.ui.demo.nav.controller.employee
 */
export default class Resume extends BaseController {
  onInit(): void {
    this.view?.setModel(new JSONModel(), "view");
    this.router
      .getRoute("employeeResume")
      ?.attachMatched(this._routeMatched, this);
  }

  onTabSelect(oEvent: Event) {
    const oCtx = this.view?.getBindingContext();
    this.router.navTo(
      "employeeResume",
      {
        employeeId: oCtx?.getProperty("EmployeeID"),
        "?query": { tab: oEvent.getParameter("selectedKey") },
      } as EmployeeResumeRouteArgs,
      {},
      true
    );
  }

  private _routeMatched(oEvent: Event) {
    const oArgs: EmployeeResumeRouteArgs = oEvent.getParameter("arguments");
    const oView = this.view;

    oView?.bindElement({
      path: `/Employees(${oArgs.employeeId})`,
      events: {
        change: this._onBindingChange.bind(this),
        dataRequested: function () {
          oView.setBusy(true);
        },
        dataReceived: function () {
          oView.setBusy(false);
        },
      },
    });

    const oQuery = oArgs["?query"];
    if (oQuery && _aValidTabKeys.includes(oQuery.tab)) {
      (oView?.getModel("view") as JSONModel).setProperty(
        "/selectedTabKey",
        oQuery.tab
      );
      if (oQuery.tab === "Hobbies" || oQuery.tab == "Notes") {
        this.router.getTargets()?.display(`resumeTab${oQuery.tab}`);
      }
    } else {
      this.router.navTo(
        "employeeResume",
        {
          employeeId: oArgs.employeeId,
          "?query": { tab: _aValidTabKeys[0] },
        } as EmployeeResumeRouteArgs,
        {},
        true
      );
    }
  }

  private _onBindingChange() {
    if (!this.view?.getBindingContext()) {
      this.router.getTargets()?.display("notFound");
    }
  }
}
